package com.finalab.website.controller;

import com.finalab.website.constant.ResponseCode;
import com.finalab.website.model.Project;
import com.finalab.website.service.ProjectService;
import com.finalab.website.util.BeanValidatorUtil;
import com.finalab.website.util.ResponseUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "/project")
public class ProjectController {

    @Autowired
    ProjectService projectService;

    @RequestMapping(value = "/getById")
    public void selectProject(int id, PrintWriter out){
        Map<String, Object> map = new HashMap<>(1);
        map.put("project", projectService.selectById(id));
        ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, map);
    }

    @RequestMapping(value = "/all")
    public void selectProject(Model model, PrintWriter out){
        model.addAttribute("projects", projectService.selectAll());
    }

    @RequestMapping(value = "/add")
    public void insert(Project project, PrintWriter out){
        if(!BeanValidatorUtil.validate(project)){
            ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
            return;
        }
        projectService.insert(project);
        ResponseUtil.responseCode(out, ResponseCode.REQUEST_SUCCESSED);
    }

    @RequestMapping(value = "/delete")
    public void delete(int id, PrintWriter out){
        projectService.delete(id);
        ResponseUtil.responseCode(out, ResponseCode.REQUEST_SUCCESSED);
    }

    @RequestMapping(value = "/update")
    public void update(Project project, PrintWriter out){
        if(!BeanValidatorUtil.validate(project)){
            ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
            return;
        }
        projectService.update(project);
        ResponseUtil.responseCode(out, ResponseCode.REQUEST_SUCCESSED);
    }
}
